package com.dm.cloud.core.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author hcx
 * @desc
 * @date 2021/10/21
 */
@Component
public class ApplicationUtil implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {

        return ApplicationUtil.applicationContext.getBean(name);
    }
    public static <T> Map<String, T> getBeans(Class<T> clazz){
        return ApplicationUtil.applicationContext.getBeansOfType(clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        return ApplicationUtil.applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return ApplicationUtil.applicationContext.getBean(name, requiredType);
    }

    public static boolean containsBean(String name) {
        return ApplicationUtil.applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    public static Class<? extends Object> getType(String name) {
        return applicationContext.getType(name);
    }
    public static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }
}
